package com.woniu.zsd.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.zsd.platform.Netty.NettyServer;
import com.woniu.zsd.platform.Netty.WebSocketFrameHandler;
import com.woniu.zsd.platform.dao.AccountMapper;
import com.woniu.zsd.platform.dto.AnnouncementDto;
import com.woniu.zsd.platform.form.PageForm;
import com.woniu.zsd.platform.model.Account;
import com.woniu.zsd.platform.model.Announcement;
import com.woniu.zsd.platform.dao.AnnouncementMapper;
import com.woniu.zsd.platform.param.AddAnnouncementParam;
import com.woniu.zsd.platform.service.AnnouncementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangtao
 * @since 2025年02月18日
 */
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnouncementService {
    @Resource
    private AccountMapper accountMapper;

    @Resource
    private AnnouncementMapper announcementMapper;// 用于存储公告数据
    private ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public void publishAnnouncement(AddAnnouncementParam param ,Integer accountId) throws Exception {
        // 发布公告
        // 1. 存储到数据库
        Announcement announcement = BeanUtil.toBean(param, Announcement.class);
        Account account = accountMapper.selectById(accountId);
        announcement.setPublisher(account.getAccountName());
        announcement.setPublishedAt(LocalDateTime.now());
        announcementMapper.insert(announcement);
        // 2. 构建只包含公告标题和发布时间的数据对象
        try {
            Map<String, Object> pushData = new HashMap<>();
            pushData.put("title", announcement.getTitle());
            pushData.put("publishedAt", announcement.getPublishedAt());

            // 3. 转换为 JSON 字符串
            String jsonMessage = objectMapper.writeValueAsString(pushData);

            // 4. 广播消息给所有已连接的 WebSocket 客户端
            WebSocketFrameHandler.broadcast(jsonMessage);
            System.out.println("公告已推送：" + jsonMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public List<AnnouncementDto> selectAnnouncement() throws Exception {
        List<Announcement> announcements = announcementMapper.selectList(null);
        List<AnnouncementDto> announcementDtos = BeanUtil.copyToList(announcements, AnnouncementDto.class);
        return announcementDtos;
    }
}
